package com.amos.muexamclient.sys.service.impl;

import com.amos.exception.BizExceptionEnum;
import com.amos.muexamclient.sys.entity.SysUserEntity;
import com.amos.muexamclient.sys.mapper.SysUserMapper;
import com.amos.muexamclient.sys.service.SysPostService;
import com.amos.muexamclient.sys.service.SysRoleService;
import com.amos.muexamclient.sys.service.SysUserService;
import com.amos.muexamclient.sys.service.dto.SysPostDTO;
import com.amos.muexamclient.sys.service.dto.SysRoleDTO;
import com.amos.muexamclient.sys.service.dto.SysUserDTO;
import com.amos.muexamclient.util.SecurityUtils;
import com.amos.muexamcore.core.AbstractPageService;
import com.amos.muexamcore.core.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Copyright © 2018 五月工作室. All rights reserved.
 *
 * @Package com.amos.muexamclient.sys.service.impl
 * @ClassName SysUserServiceImpl
 * @Description TODO
 * @Author Amos
 * @Modifier
 * @Date 2020-03-21 22:08:15
 * @Version 1.0
 **/
@Service
public class SysUserServiceImpl extends AbstractPageService<SysUserDTO, SysUserEntity> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPostService postService;

    /**
     * 条件查询
     *
     * @param dto 查询的条件
     */
    @Override
    public List<SysUserDTO> list(SysUserDTO dto) {
        return this.getMapper().select(dto);
    }

    /**
     * 返回BaseDao对象
     */
    @Override
    public BaseMapper<SysUserEntity, SysUserDTO> getMapper() {
        return sysUserMapper;
    }

    /**
     * 保存之间的校验
     *
     * @param dto 保存的对象
     */
    @Override
    public void preValidate(SysUserDTO dto) {
        this.validateUsername(dto.getUserName());
        this.validatePhone(dto.getPhonenumber(), dto.getId());
        this.validateEmail(dto.getEmail(), dto.getId());
    }

    private void validateUsername(String username) {
        SysUserDTO user = new SysUserDTO();
        user.setUserName(username);
        List<SysUserDTO> list = this.list(user);
        if (!CollectionUtils.isEmpty(list)) {
            user = list.get(0);
            BizExceptionEnum.DEFINED_EXCEPTION.definedMsg("新增用户'" + user.getUserName() + "'失败，登录账号已存在").
                    throwException();
        }
    }

    private void validateEmail(String email, String id) {
        SysUserDTO user = new SysUserDTO();
        user.setEmail(email);
        List<SysUserDTO> list = this.list(user);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        user = list.get(0);
        if (StringUtils.isEmpty(id)) {
            BizExceptionEnum.DEFINED_EXCEPTION.definedMsg("新增用户'" + user.getUserName() + "'失败，邮箱已存在").
                    throwException();
        } else {
            if (!user.getId().equalsIgnoreCase(id)) {
                BizExceptionEnum.DEFINED_EXCEPTION.definedMsg("修改用户'" + user.getUserName() + "'失败，邮箱已存在").
                        throwException();
            }
        }
    }

    private void validatePhone(String phone, String id) {
        SysUserDTO user = new SysUserDTO();
        user.setPhonenumber(phone);
        List<SysUserDTO> list = this.list(user);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        user = list.get(0);
        if (StringUtils.isEmpty(id)) {
            BizExceptionEnum.DEFINED_EXCEPTION.definedMsg("新增用户'" + user.getUserName() + "'失败，手机号已存在").
                    throwException();
        } else {
            if (!user.getId().equalsIgnoreCase(id)) {
                BizExceptionEnum.DEFINED_EXCEPTION.definedMsg("修改用户'" + user.getUserName() + "'失败，手机号已存在").
                        throwException();
            }
        }
    }

    /**
     * 添加子集数据
     *
     * @param id  主表ID
     * @param dto 主表DTO对象
     */
    @Override
    public void appendSubsidiary(String id, SysUserDTO dto) {

    }

    /**
     * 通过username获取记录
     *
     * @param username
     * @return
     */
    @Override
    public SysUserDTO getByUsername(String username) {
        SysUserDTO dto = new SysUserDTO();
        dto.setUserName(username);
        List<SysUserDTO> list = this.list(dto);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public String selectUserRoleGroup(String id) {
        List<SysRoleDTO> roles = roleService.selectRoleUserId(id);
        if (CollectionUtils.isEmpty(roles)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        roles.stream().forEach(item -> sb.append(item.getRoleName()).append(","));
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    @Override
    public String selectUserPostGroup(String id) {
        List<SysPostDTO> posts = postService.selectPostByUserId(id);
        if (CollectionUtils.isEmpty(posts)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        posts.stream().forEach(item -> sb.append(item.getPostName()).append(","));
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    @Override
    public void resetPassword(String id, String newPassword) {
        this.sysUserMapper.resetPassword(id, newPassword);
    }

    @Override
    public int resetPwd(SysUserDTO user) {
        String password = SecurityUtils.encryptPassword(user.getPassword());
        this.sysUserMapper.resetPassword(user.getId(), password);
        return 1;
    }

    @Override
    public int deleteUserByIds(String[] userIds) {
        return this.sysUserMapper.deleteUserByIds(userIds);
    }
}
